package com.vicene.gmail.product.service.impl;

import com.vicene.gmail.product.entity.SkuImagesEntity;
import com.vicene.gmail.product.entity.SpuInfoDescEntity;
import com.vicene.gmail.product.entity.SpuInfoEntity;
import com.vicene.gmail.product.service.*;
import com.vicene.gmail.product.vo.SkuItemSaleAttrVo;
import com.vicene.gmail.product.vo.SkuItemVo;
import com.vicene.gmail.product.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vicene.gmail.common.utils.PageUtils;
import com.vicene.gmail.common.utils.Query;

import com.vicene.gmail.product.dao.SkuInfoDao;
import com.vicene.gmail.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService imagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor executor;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        /**
         * key:
         * catelogId: 0
         * brandId: 0
         * min: 0
         * max: 0
         */
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){

            queryWrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("brand_id",brandId);
        }

        String min = (String) params.get("min");
        if(!StringUtils.isEmpty(min)){
            queryWrapper.ge("price",min);
        }

        String max = (String) params.get("max");

        if(!StringUtils.isEmpty(max)  ){
            try{
                BigDecimal bigDecimal = new BigDecimal(max);

                if(bigDecimal.compareTo(new BigDecimal("0"))==1){
                    queryWrapper.le("price",max);
                }
            }catch (Exception e){

            }

        }


        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id" ,spuId));
        return list;
    }

    @Override
    public SkuItemVo item(Long skuId ) throws ExecutionException, InterruptedException {

        Instant start = Instant.now();
// some code

        SkuItemVo skuItemVo = new SkuItemVo();
//
//        SkuInfoEntity info = getById(skuId);
//        skuItemVo.setInfo(info);
//
//        List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
//        skuItemVo.setImages(images);
//
//        Long spuId = info.getSpuId();
//        SpuInfoDescEntity spuInfoDescEntity =  spuInfoDescService.getById(spuId);
//        skuItemVo.setDesp(spuInfoDescEntity);
//
//        List<SkuItemSaleAttrVo> list = skuSaleAttrValueService.getSaleAttrsBySpuId(spuId);
//        skuItemVo.setSaleAttr(list);
//
//        List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(spuId , info.getCatalogId());
//        skuItemVo.setGroupAttrs(attrGroupVos);



        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() ->{
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        } , executor);


        CompletableFuture<Void> saleAttrFuture =infoFuture.thenAcceptAsync(res ->{
            List<SkuItemSaleAttrVo> list = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(list);
        }, executor);

        CompletableFuture<Void> descFuture =infoFuture.thenAcceptAsync(res ->{
            SpuInfoDescEntity spuInfoDescEntity =  spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesp(spuInfoDescEntity);
        }, executor);

        CompletableFuture<Void> baseAttrFuture =infoFuture.thenAcceptAsync(res ->{
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId() , res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, executor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(()->{
            List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);

        CompletableFuture.allOf(saleAttrFuture,descFuture,baseAttrFuture,imageFuture).get();

        Instant finish = Instant.now();
        long timeElapsed = Duration.between(start, finish).toMillis();
        System.out.println(timeElapsed);

        return skuItemVo;
    }



}